/* eslint-disable default-case */
/* eslint-disable array-callback-return */
import { message } from 'antd';
import _ from 'lodash';
import {
  increasePersonnelList,
  getProList,
  getProDetail,
  getFeedback,
  personnelexport,
  pespersonnelexport,
  freceiptfile,
  // employeecontmes,
  lookagreement,
  // stafftack,
  // paymentperstype,
  receiptinface,
  // employetask,
  notifyctring,
  backReceipt,
  receiptModification,
  getReceiptTagList,
  orderDetails,
  paymentDetailsList,
  getproselectedList,
  getcustNamesList,
  getSupplyList,
  getTwohouseMessage,
  getbatchConnec,
  cancelReceiveAddemp,
  batchReceiveOrder,
  getEmpContact,
  getInsIdeDetail,
  updateInsIde,
  insertEmpContact,
  getTaskOrinjAcc,
  getBatchId,
  getProgress,
} from '@/services/receiveordermanage';
import * as service from '@/services/socket';

export default {
  state: {
    formFieldsValue: {},
    expandForm: false,
    activeKey: '1',
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    dataList: [],
    detail: {
      detList: [],
      affixList: [],
    },
    proFbList: [],
    proBaseList: {},
    addOrEdit: {
      productList: [],
    },
    history: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    servicnftio: [], // 服务类型
    pdInfoDtos: [], // 产品服务信息
    detailsData: {},
    payDetailsData: [],
    proInsuranceList: [],
    supplyList: [],
    custList: [], // 客户下拉
    stafflxList: {},
    secAccuList: [], // 工伤二级户
    tabList: [
      { itemCode: '1', itemName: '待接单', isHas: false },
      { itemCode: '2', itemName: '已接单', isHas: false },
      { itemCode: '3', itemName: '已回单', isHas: false },
      { itemCode: '4', itemName: '问题人员', isHas: false },
      { itemCode: '5', itemName: '已取消', isHas: false },
    ],
    empContactList: {}, // 获取员工联系详情数据
    injAccParams: {}, // 二级户查询参数
    injAccList: {
      // 设置工伤二级户列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    allInjAccList: [], // 所有的二级户弹框数据
    isHasTask: false,
    selectedData: {},
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '接单任务', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/nsApi/recvAdd/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    // 待接单查看详情
    *feactorderDetail({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(orderDetails, payload);
      const sortNumber = (a, b) => a.operLeafType - b.operLeafType;
      if (response.success) {
        if (response.data.execStatusDto && response.data.execStatusDto.leafList) {
          response.data.execStatusDto.leafList = response.data.execStatusDto.leafList.sort(
            sortNumber
          );
        }
        yield put({
          type: 'orderDetails',
          payload: response.data,
        });
      }
      callback(response);
    },
    // 获取缴纳明细列表
    *getcustNamesList({ payload, callback }, { call, put }) {
      const response = yield call(getcustNamesList, payload);
      if (response.success) {
        yield put({
          type: 'getCustDataList',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '服务器端错误');
      }
      return callback && callback(response);
    },

    // 获取缴纳明细列表
    *getPaymentDetails({ payload }, { call, put }) {
      const response = yield call(paymentDetailsList, payload);
      if (response.success) {
        yield put({
          type: 'getPayDataList',
          payload: response.data,
        });
      } else {
        message.warning('查询失败！');
      }
    },

    // 获取问题对象的险种
    *selectedRowsList({ payload }, { call, put }) {
      const payloads = {
        recvAddTaskIds: payload,
      };
      const response = yield call(getproselectedList, payloads);
      if (response.success) {
        yield put({
          type: 'getProInsuranceList',
          payload: response,
        });
      } else {
        message.warning(response.message || '查询失败！');
      }
      return response;
    },

    //
    // selectedRowsList({ payload }, { call, put }) {
    //   console.log(payload);
    //   const response = yield call(getproselectedList, {});
    //   // if (response.success) {
    //   //   console.log(response);
    //   //   // yield put({
    //   //   //   type: 'getPayDataList',
    //   //   //   payload: response.data,
    //   //   // });
    //   // } else {
    //   //   message.error('查询失败！');
    //   // }
    // },

    // 列表数据
    *fetchList({ payload }, { call, put }) {
      const response = yield call(increasePersonnelList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: {},
          currentPage,
          pageSize,
        },
      });

      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getProList',
        payload: {
          data: {},
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getProList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 问题人员详情
    *feactProDetail({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      yield put({
        type: 'getProDetail',
        payload: {},
      });
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '查询失败：服务端未知错误');
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback = () => {} }, { call }) {
      const response = yield call(getFeedback, payload);
      callback(response);
    },

    // 员工联系
    // *stafflx({ payload, callback }, { call, put }) {
    //   const response = yield call(stafftack, payload);
    //   if (response.success) {
    //     yield put({
    //       type: 'getstafflxList',
    //       payload: { data: response.data },
    //     });
    //   }
    //   callback && callback(response);
    // },

    // 缴费人员类别
    // *perprotype({ payload, callback }, { call, put }) {
    //   const response = yield call(paymentperstype, payload);
    //   callback && callback(response);
    // },

    // 回单
    *receiptId({ payload, callback }, { call }) {
      const response = yield call(backReceipt, payload);
      if (callback) {
        callback(response);
      }
    },

    // 回单修改
    *modification({ payload, callback }, { call }) {
      const response = yield call(receiptModification, payload);
      if (callback) {
        callback(response);
      }
    },

    // 已接单文件导出
    *outexportFile({ payload }, { call }) {
      const response = yield call(personnelexport, payload);
      const blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, payload.fileName);
      } else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = payload.fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    },
    // 接单
    *receiptFile({ payload, callback }, { call }) {
      const response = yield call(freceiptfile, payload);
      callback(response);
    },

    // 员工联系
    // *lemployeecont({ payload, callback }, { call, put }) {
    //   const response = yield call(employeecontmes, payload);
    // },

    // 查看协议
    *seeagreement({ payload, callback }, { call, put }) {
      // debugger
      const response = yield call(lookagreement, payload);
      // const {} = payload;
      if (response.success) {
        yield put({
          type: 'getseeagreementList',
          payload: { data: response.data },
        });
      } else {
        yield put({
          type: 'getseeagreementList',
          payload: { data: [] },
        });
      }
      callback(response);
    },

    // 员工联系
    // *employeconta({ payload, callback }, { call, put }) {
    //   const response = yield call(employetask, payload);
    //   callback(response);
    // },

    *notifyc({ payload, callback }, { call }) {
      const response = yield call(notifyctring, payload);
      callback(response);
    },

    // 回单
    *receiptback({ payload, callback }, { call, put }) {
      const response = yield call(receiptinface, payload);
      if (response.success) {
        yield put({
          type: 'receiptinfacemessage',
          payload: { data: response.data },
        });
      } else {
        message.warning(response.message || '查询失败');
      }
      callback(response);
    },

    // 查询页签数量
    *getReceiptTagData({ payload, callback }, { call }) {
      const response = yield call(getReceiptTagList, payload);
      if (response.success) {
        if (callback) {
          callback(response.data);
        }
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取供应商列表
    *fetchSupplyList({ payload }, { call, put }) {
      const response = yield call(getSupplyList, payload);
      yield put({
        type: 'getSupplyList',
        payload: Array.isArray(response.data) ? response.data : [],
      });
    },

    // 问题人员文件导出
    *quesoutexportFile({ payload }, { call }) {
      const response = yield call(pespersonnelexport, payload);
      const blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=UTF-8' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, payload.fileName);
      } else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = payload.fileName;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
      }
    },

    // 获取工伤二级户数据
    *getTwohouseData({ payload, callback }, { call, put }) {
      const response = yield call(getTwohouseMessage, payload);
      if (response.success) {
        if (response.data.flag) {
          yield put({
            type: 'getTwohouseDatas',
            payload: response.data,
          });
        }

        if (callback) {
          callback(response.data);
        }
      } else {
        message.warning('查询失败！');
      }
    },
    *batchConnec({ payload, callback }, { call }) {
      const response = yield call(getbatchConnec, payload);
      if (response.success) {
        message.success('接单成功！');
        callback(response);
      } else {
        message.warning(response.message || '接单失败！');
        callback(response);
      }
    },
    // 取消接单
    *cancelReceive({ payload }, { call }) {
      const response = yield call(cancelReceiveAddemp, payload);
      return response;
    },

    // 批量接单
    *batchReceiveOrder({ payload }, { call, put }) {
      const response = yield call(batchReceiveOrder, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data.batchNo },
        });
      }
      return response;
    },
    // 获取页签数量
    *fetchTabNum({ payload }, { call, put, select }) {
      const response = yield call(getReceiptTagList, payload.formFieldsValue);
      let activeKey = yield select(state => state.addemprec.activeKey);
      const tabList = yield select(state => state.addemprec.tabList);
      if (response.success) {
        if (response.data && response.data.length) {
          const sortNumber = (a, b) => a.itemCode - b.itemCode;
          const tabCodeArr = response.data.sort(sortNumber);
          const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.tabHdl}` === activeKey); // 当前页签有没有查询到
          if (!isHasBadgeCurrentTab) {
            activeKey = `${tabCodeArr[0].tabHdl}`;
          }
          tabCodeArr.forEach(item => {
            if (`${item.tabHdl}` !== activeKey) {
              tabList[item.tabHdl - 1].isHas = true;
            }
          });
          yield put({
            type: 'updateModelData',
            payload: { activeKey, tabList },
          });
          const getListParams = {
            ...payload.formFieldsValue,
            pageArg: { currentPage: payload.currentPage, pageSize: payload.pageSize },
          };
          if (activeKey === '4') {
            if (payload.formFieldsValue) {
              yield put({
                type: 'updateModelData',
                payload: {
                  ...payload.formFieldsValue,
                },
              });
            }
            yield put({
              type: 'problempage/getProList',
              payload: {
                ...getListParams,
                busiType: '8',
              },
            });
          } else {
            yield put({
              type: 'fetchList',
              payload: { ...getListParams, hdlState: activeKey },
            });
          }
        } else {
          yield put({
            type: 'getList',
            payload: {
              data: { pagerVo: {} },
              currentPage: 1,
              pageSize: 10,
            },
          });
          if (activeKey === '4') {
            yield put({
              type: 'problempage/updateProList',
              payload: {
                data: [],
                currentPage: 1,
                pageSize: 10,
              },
            });
          }
        }
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },

    // 获取员工联系详情信息  author-xxl
    *getEmpContactDetail({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(getEmpContact, payload);
      if (response.success) {
        yield put({
          type: 'getEmpContact',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '获取员工联系信息：服务器端错误');
      }
      callback(response.data);
    },
    // 获取缴费人员类别信息 author-xxl
    *getInsIdeList({ payload, callback = () => {} }, { call }) {
      const response = yield call(getInsIdeDetail, payload);
      callback(response);
    },
    // 修改缴费人员类别 author-xxl
    *updateInsIde({ payload, callback = () => {} }, { call }) {
      const response = yield call(updateInsIde, payload);
      callback(response);
    },
    // 员工联系提交数据 author-xxl
    *insertEmpContact({ payload, callback = () => {} }, { call }) {
      const response = yield call(insertEmpContact, payload);
      callback(response);
    },

    // 批量接单任务：获取任务id或者二级户列表
    *getTaskOrinjAcc({ payload }, { call, put, select }) {
      const {
        pageArg: { currentPage, pageSize },
        ...resetParams
      } = payload;
      const response = yield call(getTaskOrinjAcc, payload);
      let allInjAccList = yield select(state => state.addemprec.allInjAccList);
      yield put({
        type: 'updateModelData',
        payload: {
          injAccList: {
            list: [],
            pagination: {
              current: currentPage,
              pageSize,
            },
          },
          injAccParams: resetParams,
        },
      });
      if (response.success && response.data) {
        if (response.data.pageRecords && response.data.pageRecords.length) {
          // 获取工伤二级户列表
          const data = response.data.pageRecords;
          data.map(item => {
            const temp = item;
            temp.injecIdList = undefined;
            temp.key = `${temp.sendSuppId}_${temp.custId}`;
            if (temp.injAccInfo && temp.injAccInfo.length) {
              temp.injAccInfo.map(values => {
                const tem = values;
                tem.value = tem.accoId;
                tem.label = tem.accoName;
                tem.isLeaf = (tem.injSecAccoDtos && false) || true;
                if (tem.injSecAccoDtos && tem.injSecAccoDtos.length) {
                  const children = [];
                  tem.injSecAccoDtos.map(c => {
                    children.push({
                      value: c.injSecAccoId,
                      label: c.injSecAccoName,
                      isLeaf: true,
                    });
                  });
                  tem.children = children;
                }
              });
              const i = _.findIndex(allInjAccList, { key: temp.key });
              if (i > -1) {
                temp.injecIdList = allInjAccList[i].injecIdList;
              } else if (
                temp.injAccInfo.length === 1 &&
                temp.injAccInfo[0].injSecAccoDtos &&
                temp.injAccInfo[0].injSecAccoDtos.length === 1
              ) {
                temp.injecIdList = [
                  temp.injAccInfo[0].accoId,
                  temp.injAccInfo[0].injSecAccoDtos[0].injSecAccoId,
                ];
              }
            }
          });

          allInjAccList = _.uniqBy([...allInjAccList, ...data], 'key');
          yield put({
            type: 'updateModelData',
            payload: {
              injAccList: {
                list: data,
                pagination: {
                  total: response.data && response.data.totalCount,
                  current: currentPage,
                  pageSize,
                },
              },
              allInjAccList,
            },
          });
        } else if (response.data && !response.data.totalCount) {
          yield put({
            type: 'uploadFileWithProgress',
            payload: { isBatch: true, params: { ...resetParams } },
          });
          return response;
        }
      } else {
        message.warning(response.message || '获取接单信息：服务器端错误');
      }
      return response;
    },
    // 批量接单任务：获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getProgress, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.successProp },
        });
      }
      return response;
    },
    // 上传文件:批量进度:获取batchId后获取进度
    *uploadFileWithProgress(
      {
        payload: { isBatch, params },
      },
      { call, put }
    ) {
      const response = yield call(isBatch ? batchReceiveOrder : getBatchId, params);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data && response.data.batchId,
            progressPercent: 0,
          },
        });
        if (response.data && response.data.successProp !== 100) {
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
            },
          });
          yield call(service.socketChannel, {
            type: 'sub',
            data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          });
        } else {
          yield put({
            type: 'updateBatchTask',
            payload: response.data,
          });
        }
      } else {
        // 上传失败
        message.warning(`${response.message || '上传失败'}`);
      }
      return response;
    },

    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.addemprec);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
  },

  reducers: {
    // 查看列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list =
        data.pagerVo && data.pagerVo.pageRecords && Array.isArray(data.pagerVo.pageRecords)
          ? data.pagerVo.pageRecords
          : [];
      const { countVo } = data;
      return {
        ...state,
        data: {
          list,
          countVo,
          pagination: {
            total: data.pagerVo && data.pagerVo.totalCount && data.pagerVo.totalCount,
            current: currentPage,
            pageSize,
          },
        },
      };
    },

    // 查看协议
    getseeagreementList(
      state,
      {
        payload: { data },
      }
    ) {
      const list = Array.isArray(data) ? data : [];
      return {
        ...state,
        data: {
          list,
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      };
    },

    // 回单
    receiptinfacemessage(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        data,
      };
    },

    dicList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        servicnftio: data,
      };
    },

    // 获取问题人员列表
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos || [],
      };
    },

    // 发单增员 - 详情
    orderDetails(state, { payload }) {
      return {
        ...state,
        detailsData: payload,
      };
    },
    // 点击缴纳明细时
    getPayDataList(state, { payload }) {
      return {
        ...state,
        payDetailsData: payload,
      };
    },

    // 员工联系
    // getstafflxList(state, { payload }) {
    //   return {
    //     ...state,
    //     stafflxList: payload.data,
    //   };
    // },

    // 文件导出
    exportFile(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos,
      };
    },

    // 取消分项
    newpdInfoDtosList(state, { payload }) {
      const temp = state;
      temp.data.pdInfoDtos = payload;
      return {
        ...state,
        data: state.data,
      };
    },
    // 分项
    addpdInfoDtosList(state, { payload }) {
      const temp = state;
      temp.data.pdInfoDtos = payload;
      return {
        ...state,
        data: state.data,
      };
    },
    // 客户下拉数据
    getCustDataList(state, { payload }) {
      return {
        ...state,
        custList: payload,
      };
    },

    // 标记问题人员的问题对象列表
    getProInsuranceList(state, { payload }) {
      return {
        ...state,
        proInsuranceList: payload.data,
      };
    },
    getSupplyList(state, { payload }) {
      return {
        ...state,
        supplyList: payload,
      };
    },

    // 工伤二级户
    getTwohouseDatas(state, { payload }) {
      if (payload.injSecList.length > 0) {
        payload.injSecList.map(item => {
          const temp = item;
          temp.value = temp.accoId;
          temp.label = temp.accoName;
          temp.children = temp.injSecAccoDtos;
        });
      }

      if (payload.injSecList.length > 0) {
        payload.injSecList.map(it => {
          it.children.map(items => {
            const temp = items;
            temp.value = temp.injSecAccoId;
            temp.label = temp.injSecAccoName;
          });
        });
      }
      return {
        ...state,
        secAccuList: payload.injSecList,
      };
    },

    // 获取员工联系详情信息
    getEmpContact(state, { payload }) {
      return {
        ...state,
        empContactList: payload,
      };
    },

    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHas = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { resultInfo, currentStep } = state;
      if (payload.successProp === 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
      }
      return {
        ...state,
        progressPercent: payload.successProp,
        resultInfo,
        currentStep,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'task':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
